package com.taijia.chapter6;

import org.apache.commons.lang3.ArrayUtils;

import com.alibaba.fastjson.JSON;

public class PackageClass {

	/**
	 * parse String to double[][]
	 * @param sourceStr
	 * @return
	 */
	public static double[][] parse(String sourceStr) {
		String[] strArray = sourceStr.split(";");
		double[][] result = new double[0][];
		for (String str : strArray) {
			// 这个有点像php 的array_push 或这 js 的push 不需要知道二维数组的长度
			result = ArrayUtils.add(result,convert(str.split(",")));
		}
		return result;
	}
	
	/**
	 * convert String[] to double[][]
	 * @param strArray
	 * @return
	 */
	private static double[] convert(String[] strArray) {
		if(strArray == null || strArray.length==0) 
			return null;
		double[] result = new double[0];
		for (String str : strArray) {
			// 这个有点像php 的array_push 或这 js 的push 不需要知道二维数组的长度
			result = ArrayUtils.add(result, Double.parseDouble(str));
		}
		return result;
	}
	
	/**
	 * parse String[] to double[][] by mashibin
	 * @param sourceStr
	 * @return
	 */
	private static double[][] parseOrdinary(String sourceStr) {
		String[] sourceStrArr = sourceStr.split(";");
		double[][] result = new double[sourceStrArr.length][];
		if(sourceStrArr.length > 0) {
			for (int i = 0; i < sourceStrArr.length; i++) {
				String[] sourceStrArrArr = sourceStrArr[i].split(",");
				if(sourceStrArrArr.length > 0) {
					result[i] = new double[sourceStrArrArr.length];
					for (int j = 0; j < sourceStrArrArr.length; j++) {
						result[i][j] = Double.parseDouble(sourceStrArrArr[j]);
					}
				}
			}
		}
		return result;
	}
	
	public static void main(String[] args) {
		final String str = "3,4,5;3,2;22,7;1";
		System.out.println(JSON.toJSONString(parse(str))); // my function
		System.out.println(JSON.toJSONString(parseOrdinary(str))); // mashibin`s function
	}
	
}
